关于python:在matplotlib中保存一个子图

您所在的位置:网站首页 matplotlib 保存图像 关于python:在matplotlib中保存一个子图

关于python:在matplotlib中保存一个子图

2024-05-22 06:31| 来源: 网络整理| 查看: 265

是否可以在matplotlib图形中保存(另存为png)单个子图? 假设我有

12345import pyplot.matplotlib as plt ax1 = plt.subplot(121) ax2 = plt.subplot(122) ax1.plot([1,2,3],[4,5,6])     ax2.plot([3,4,5],[7,8,9])

是否可以将两个子图分别保存到不同的文件中,或者至少将它们分别复制到一个新的图形中以进行保存?

我在RHEL 5上使用了matplotlib的1.0.0版本。

谢谢,

罗伯特

尽管@Eli是非常正确的,通常通常不需要这样做,但有可能。 savefig带有bbox_inches自变量,可用于将图形的仅一部分选择性地保存到图像。

这是一个简单的示例:

123456789101112131415161718192021import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # Make an example plot with two subplots... fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax1.plot(range(10), 'b-') ax2 = fig.add_subplot(2,1,2) ax2.plot(range(20), 'r^') # Save the full figure... fig.savefig('full_figure.png') # Save just the portion _inside_ the second axis's boundaries extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) fig.savefig('ax2_figure.png', bbox_inches=extent) # Pad the saved area by 10% in the x-direction and 20% in the y-direction fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

完整图:

第二个子图内的区域:

第二个子图周围的区域在x方向上填充了10%,在y方向上填充了20%:

相关讨论 +1:哇! 我希望在尝试了解有关Matplotlib的更多信息时遇到了这些方法! 如果官方文档将感兴趣的读者引导到Matplotlib的这些有用的角落,并且相关概念的表述更加结构化,那就太好了。 :) 非常感谢,这就是我想要的! 有一天你不学习新东西是糟糕的一天...做得好++ 如果使用extent.expanded()方法,如何减少产生的图形顶部和右侧的冗余空间? 我们可以精确地在农产品造型的四个侧面中的每个侧面指定空间吗? 那太好了。 神奇。 我不知道你想通了。

在3年后的@Joe中将full_extent()函数应用到答案中,您可以确切地得到OP所需要的。 另外,您可以使用Axes.get_tightbbox()来使边框更紧密

12345678910111213141516171819202122232425262728293031323334import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from matplotlib.transforms import Bbox def full_extent(ax, pad=0.0):    """Get the full extent of an axes, including axes labels, tick labels, and     titles."""     # For text objects, we need to draw the figure first, otherwise the extents     # are undefined.     ax.figure.canvas.draw()     items = ax.get_xticklabels() + ax.get_yticklabels() #    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]     items += [ax, ax.title]     bbox = Bbox.union([item.get_window_extent() for item in items])     return bbox.expanded(1.0 + pad, 1.0 + pad) # Make an example plot with two subplots... fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax1.plot(range(10), 'b-') ax2 = fig.add_subplot(2,1,2) ax2.plot(range(20), 'r^') # Save the full figure... fig.savefig('full_figure.png') # Save just the portion _inside_ the second axis's boundaries extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted()) # Alternatively, # extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted()) fig.savefig('ax2_figure.png', bbox_inches=extent)

我发布了一张图片,但是我没有信誉点

相关讨论 通过添加项目+ = [ax.get_xaxis()。get_label(),ax.get_yaxis()。get_label()],可以将该答案扩展为包括文本标签。 在我添加它们之前,它们已被切断。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3